package com.sesame.controller;

import kim.sesame.common.web.controller.AbstractWebController;
import kim.sesame.common.result.ApiResult;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 消费
 */
@CommonsLog
@RestController
@RequestMapping("/test")
public class TestController extends AbstractWebController {

    final static String SERVICE_URL = "http://spring-cloud-example-ribbon-service";

    @Autowired
    RestTemplate restTemplate;

    /**
     * http://127.0.0.1:8092/test/getData?name=111
     * @param name
     * @return
     */
    @RequestMapping("/getData")
    public ApiResult getData(String name){
        log.info(name);
        String str = restTemplate.getForObject(SERVICE_URL+"/test/getData", String.class);

        return success(str);
    }

    /**
     * http://127.0.0.1:8092/test/getReq?name=aaa&pwd=bbb
     * get 请求传参数
     * @return
     */
    @RequestMapping("/getReq")
    public ApiResult getReq(String name,String pwd){
        Map<String,String> params = new HashMap<>();
        params.put("name",name);
        params.put("pwd",pwd);

        System.out.println(params);

        String url = SERVICE_URL+"/test/testReqType";

//        String res = restTemplate.getForObject(url, String.class, params);// 好像是版本变更,这样传参数已经不起作用了

        String res = restTemplate.getForObject(url+"?name="+name+"&pwd="+pwd, String.class);
        return success(res);
    }

    /**
     * http://127.0.0.1:8092/test/postReq?name=aaa&pwd=bbb
     * post 请求传参数
     * @return
     */
    @RequestMapping("/postReq")
    public ApiResult postReq(String name,String pwd){
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("name",name);
        paramMap.add("pwd",pwd);

        String url = SERVICE_URL+"/test/testReqType";
        String res = restTemplate.postForObject(url, paramMap, String.class);
        return success(res);
    }
}
